package com.zifeng.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zifeng.dao.BlockDao;
import com.zifeng.dao.TransactionDao;
import com.zifeng.pojo.Block;
import com.zifeng.pojo.Order;
import com.zifeng.pojo.Transaction;
import com.zifeng.service.IBlockService;
import com.zifeng.service.impl.TransactionServiceImpl;
import com.zifeng.utils.BlockCache;
import com.zifeng.utils.CryptoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * 区块链核心服务
 */
@Service
public class BlockServiceImpl extends ServiceImpl<BlockDao, Block> implements IBlockService {

    @Autowired
    private BlockCache blockCache;

    @Autowired
    private BlockDao blockDao;

    @Autowired
    private TransactionDao transactionDao;

    @Autowired
    private TransactionServiceImpl transactionService;

    /**
     * 创建创世区块
     *
     * @return
     */
    public Block createGenesisBlock() {
        Block genesisBlock = new Block();
        //设置创世区块高度为1
        genesisBlock.setBlockIndex((1L));
        genesisBlock.setBlockTimestamp(new Timestamp(System.currentTimeMillis()));
        genesisBlock.setNonce(1);
        //封装业务数据
        List<Transaction> tsaList = new ArrayList<Transaction>();
        Order order = new Order();
        Transaction tsa = new Transaction();
        tsa.setId(1L);
        tsa.setBusinessInfo("这是创世区块, 初始订单：" + JSON.toJSONString(order));
        tsaList.add(tsa);
        genesisBlock.setTransactions(tsaList);
        //设置创世区块的hash值
        genesisBlock.setBlockHash(calculateHash("", tsaList, 1));
        //添加业务数据集合到数据库中
        tsa.setBlockId(genesisBlock.getBlockIndex());
        transactionDao.insert(tsa);
        //添加到区块链中
        blockDao.insert(genesisBlock);
        return genesisBlock;
    }

    /**
     * 创建新区块
     *
     * @param nonce
     * @param previousHash
     * @param hash
     * @param blockTxs
     * @return
     */
    public Block createNewBlock(int nonce, String previousHash, String hash, List<Transaction> blockTxs) {
        List<Block> blocks = getBlockChain();
        Block block = new Block();
        block.setBlockIndex(blocks.size() + 1L);
        //时间戳
        block.setBlockTimestamp(new Timestamp(System.currentTimeMillis()));
        block.setTransactions(blockTxs);
        //工作量证明，计算正确hash值的次数
        block.setNonce(nonce);
        //上一区块的哈希
        block.setPreviousHash(previousHash);
        //当前区块的哈希
        block.setBlockHash(hash);
        if (addBlock(block)) {
            return block;
        }
        return null;
    }

    /**
     * 添加新区块到当前节点的区块链中
     *
     * @param newBlock
     */
    public boolean addBlock(Block newBlock) {
        Block latestBlock = blockCache.getLatestBlock();
        //先对新区块的合法性进行校验
        if (isValidNewBlock(newBlock, latestBlock)) {
            List<Transaction> transactions = newBlock.getTransactions();
            for (Transaction transaction : transactions) {
                QueryWrapper<Transaction> wrapper = new QueryWrapper<>();
                wrapper.eq("business_info", transaction.getBusinessInfo());
                Transaction sqlTransaction = transactionDao.selectOne(wrapper);
                if (sqlTransaction == null) {
                    transactionDao.insert(transaction);
                }
            }
            blockDao.insert(newBlock);
            return true;
        }
        return false;
    }

    /**
     * 验证新区块是否有效
     *
     * @param newBlock
     * @param previousBlock
     * @return
     */
    public boolean isValidNewBlock(Block newBlock, Block previousBlock) {
        if (!previousBlock.getBlockHash().equals(newBlock.getPreviousHash())) {
            System.out.println("新区块的前一个区块hash验证不通过");
            return false;
        } else {
            // 验证新区块hash值的正确性
            String hash = calculateHash(newBlock.getPreviousHash(), newBlock.getTransactions(), newBlock.getNonce());
            if (!hash.equals(newBlock.getBlockHash())) {
                System.out.println("新区块的：" + newBlock.getPreviousHash() + " " + newBlock.getTransactions() + " " + newBlock.getNonce());
                System.out.println("新区块的hash无效: " + hash + " " + newBlock.getBlockHash());
                return false;
            }
            if (!isValidHash(newBlock.getBlockHash())) {
                return false;
            }
        }

        return true;
    }

    /**
     * 验证hash值是否满足系统条件
     *
     * @param hash
     * @return
     */
    public boolean isValidHash(String hash) {
        return hash.startsWith("0000");
    }

    /**
     * 验证整个区块链是否有效
     *
     * @param chain
     * @return
     */
    public boolean isValidChain(List<Block> chain) {
        Block block = null;
        Block lastBlock = chain.get(0);
        int currentIndex = 1;
        while (currentIndex < chain.size()) {
            block = chain.get(currentIndex);

            if (!isValidNewBlock(block, lastBlock)) {
                return false;
            }

            lastBlock = block;
            currentIndex++;
        }
        return true;
    }

    public List<Block> getBlockChain() {
        List<Block> blocks = blockDao.selectList(null);
        return blocks;
    }

    public List<Transaction> getPackedTransactions() {
        List<Transaction> transactions = transactionDao.selectList(null);
        return transactions;
    }

    /**
     * 替换本地区块链
     *
     * @param newBlocks
     */
    public void replaceChain(List<Block> newBlocks) {

        List<Block> localBlockChain = getBlockChain();
        List<Transaction> localPackedTransactions = getPackedTransactions();
        if (isValidChain(newBlocks) && newBlocks.size() > localBlockChain.size()) {
            localBlockChain = newBlocks;
            //替换已打包保存的业务数据集合
            localPackedTransactions.clear();
            localBlockChain.forEach(block -> {
                localPackedTransactions.addAll(block.getTransactions());
            });
            blockDao.delete(null);
            this.saveBatch(localBlockChain);
            transactionDao.delete(null);
            transactionService.saveBatch(localPackedTransactions);
            System.out.println("替换后的本节点区块链：" + JSON.toJSONString(getBlockChain()));
        } else {
            System.out.println("接收的区块链无效");
        }
    }

    /**
     * 计算区块的hash
     *
     * @param previousHash
     * @param currentTransactions
     * @param nonce
     * @return
     */
    public String calculateHash(String previousHash, List<Transaction> currentTransactions, int nonce) {
        return CryptoUtil.SHA256(previousHash + JSONArray.toJSONString(currentTransactions) + nonce);
    }

}
